package com.dongdongshop.service.impl;

import com.dongdongshop.data.Result;
import com.dongdongshop.domain.model.TbUser;
import com.dongdongshop.domain.model.TbUserExample;
import com.dongdongshop.domain.vo.TbUserVO;
import com.dongdongshop.mapper.TbUserMapper;
import com.dongdongshop.service.UserService;
import com.dongdongshop.util.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private TbUserMapper userMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public TbUserVO userByName(String username) {
        TbUserExample example = new TbUserExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<TbUser> userList = userMapper.selectByExample(example);
        List<TbUserVO> voList = userList.stream().map(tbUser -> {
            TbUserVO vo = new TbUserVO();
            BeanUtils.copyProperties(tbUser, vo);
            return vo;
        }).collect(Collectors.toList());
        return voList == null || voList.isEmpty() ? null : voList.get(0);
    }

    @Override
    public void selectUserName(String username) throws Exception {
        TbUserExample example = new TbUserExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<TbUser> userList = userMapper.selectByExample(example);
        if (userList != null && userList.size() > 0){
            throw new Exception();
        }
    }

    @Override
    public Result addUser(TbUserVO userVO) {
        //判断验证码是否正确
        String str = redisTemplate.opsForValue().get(userVO.getPhone());
        String num = userVO.getNum();
        if (!Objects.equals(num,str)){
            return Result.FALL().setData("验证码错误, 请重新输入");
        }
        //密码加密
        String password = userVO.getPassword();
        String s = ShiroUtils.generateSalt(6);
        String md5 = ShiroUtils.encryptPassword("MD5", password, s, 3);
        userVO.setPassword(md5);
        userVO.setSalt(s);
        //设置创建时间
        userVO.setCreated(new Date());
        //设置状态
        userVO.setStatus("Y");

        TbUser user = new TbUser();
        BeanUtils.copyProperties(userVO,user);
        //增加
        userMapper.insertSelective(user);
        return Result.OK();
    }
}
